package com.atguigu.gmall.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 拦截器  远程调用
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    //请求处理  入参：新的请求入参   远程调用时 发出请求
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1：获取到当前项目的请求

        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if(null != requestAttributes){
            HttpServletRequest request = requestAttributes.getRequest();
            if(null != request){
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                //2:将请求头中 真实用户ID 临时用户 设置到 RequestTemplate 远程调用请求
                if(!StringUtils.isEmpty(userId)){
                    requestTemplate.header("userId",userId);
                }
                if(!StringUtils.isEmpty(userTempId)){
                    requestTemplate.header("userTempId",userTempId);
                }
            }
        }





    }
}
